package com.joycessh.common.exception;

import cn.hutool.json.JSONUtil;
import com.joycessh.common.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author Joycessh
 * @Description
 * @Date 8/17/19 4:23 PM
 */
@Slf4j
@ControllerAdvice
public class GobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, HttpServletResponse res, Exception e) {
        log.error("[Error]=====捕捉到全局异常=====>", e);

        if (req.getHeader("accept").contains("application/json")
            || req.getHeader("X-Requested-With") != null
            && req.getHeader("X-Requested-With").contains("XMLHttpRequest")) {
            try {
                System.out.println(e.getMessage());
                Result result = Result.fail(e.getMessage(), "some error data");

                res.setCharacterEncoding("UTF-8");
                PrintWriter writer = res.getWriter();
                writer.write(JSONUtil.toJsonStr(result));
                writer.flush();
            }catch (IOException ioe) {
                ioe.printStackTrace();
            }
            return null;
        }

        if (e instanceof HwException) {

        }

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exception", e);
        modelAndView.addObject("message", e.getMessage());
        modelAndView.addObject("url", req.getRequestURL());
        modelAndView.setViewName("error");
        return modelAndView;
    }
}
